from django.forms.models import model_to_dict
from django.http import JsonResponse
from django.db import models
import logging
class ErrorResp(Exception):
    def __init__(self,code,msg,data):
        self.code = code
        self.message = msg
        self.data = data
    @classmethod
    def ERROR(cls,code=400,msg="服务器发生错误，操作失败！"):
        resp = cls(code,msg,{})
        return resp
    
class Response():
    def __init__(self,code,msg,data):
        self.code = code
        self.message = msg
        self.data = data

    @staticmethod
    def ERROR(code=400,msg="系统发生未知错误"):
        return ErrorResp.ERROR(code=code,msg=msg)
    @classmethod
    def SUCCESS(cls,code=200,msg="OK",data={}):
        if isinstance(data,models.Model):
            resp = cls(code,msg,model_to_dict(data))
        elif isinstance(data,dict):
            resp = cls(code,msg,data)
        else:
            logging.error("参数类型错误，必须是 DICT 或者 MODLE")
        return JsonResponse(resp.__dict__)

USER_EXIT_ERROR = Response.ERROR(code=350,msg="该用户以存在，创建用户失败")
PASSWD_ERROR = Response.ERROR(code=306,msg="用户名或密码错误")
USER_NOT_EXIT_ERROR = Response.ERROR(code=307,msg="该用户不存在")
NOT_UPLOAD_FILE_ERROR = Response.ERROR(code=308,msg="未上传任何文件")
PARAMS_ERROR = Response.ERROR(code=309,msg="参数错误，请检查参数")
UNKNOW_ERROR = Response.ERROR(code=400,msg="未知错误，请联系管理员")
HAS_BENN_DO_ERROR = Response.ERROR(code=310,msg="该操作已经提交，请勿重复提交")
TOKEN_ERROR = Response.ERROR(code=311,msg="token 已经过期 或 token错误，请重新登陆")